class WebSocketClient {
    constructor(url) {
        this.url = url;
        this.ws = null;
        this.isManualClose = false;
        this.reconnectInterval = 1000; // 重连间隔3秒
        this.heartbeatInterval = 1000; // 心跳间隔30秒
        this.heartbeatTimeout = 15000; // 心跳超时15秒
        this.reconnectTimer = null;
        this.heartbeatTimer = null;
        this.serverTimeoutTimer = null;
        this.messageCallback = null;
        this.isreconnect = false

        this.connect()
    }

    connect() {
        if (this.ws) {
            this.ws.close();
        }
        this.ws = new WebSocket(this.url);
        this.isManualClose = false;
        this.ws.onopen = () => {
            console.log('WebSocket connected');
            // this.startHeartbeat();
            this.clearReconnect();
        };

        this.ws.onmessage = (event) => {
            this.handleMessage(event.data);
            this.resetServerTimeout();
        };

        this.ws.onclose = (event) => {
            console.log('WebSocket closed:', event);
            this.handleClose(event);
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            this.ws.close();
        };
    }

    startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            if (this.ws?.readyState === WebSocket.OPEN) {
                this.sendMessage('__HEARTBEAT__');
                this.serverTimeoutTimer = setTimeout(() => {
                    console.warn('Server heartbeat timeout');
                    this.ws.close();
                }, this.heartbeatTimeout);
            }
        }, this.heartbeatInterval);
    }

    resetServerTimeout() {
        clearTimeout(this.serverTimeoutTimer);
    }

    handleMessage(data) {
        if (data === '__HEARTBEAT__') return;

        let parsedData = data;
        // 尝试将JSON字符串转换为对象
        if (typeof data === 'string') {
            try {
                parsedData = JSON.parse(data);
            } catch (error) {
                console.warn('接收到的消息不是有效的JSON格式:', error);
                // 如果解析失败，保持原始数据
            }
        }

        if (this.messageCallback) this.messageCallback(parsedData);
    }

    handleClose(event) {
        this.clearTimers();
        if (!this.isManualClose) {
            this.reconnectTimer = setTimeout(() => {
                console.log('Attempting reconnect...');
                this.isreconnect = true
                this.connect();
            }, this.reconnectInterval);
        }
    }

    clearReconnect() {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
    }

    clearTimers() {
        clearInterval(this.heartbeatTimer);
        clearTimeout(this.serverTimeoutTimer);
        this.heartbeatTimer = null;
        this.serverTimeoutTimer = null;
    }

    onMessage(callback) {
        this.messageCallback = callback;
    }

    sendMessage(data) {
        if (this.ws?.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(data));
        } else {
            console.error('WebSocket not connected');
        }
    }

    close() {
        this.isManualClose = true;
        this.clearReconnect();
        if (this.ws) {
            this.ws.close();
        }
    }
}

export default WebSocketClient